<template>
	<view>
		<!-- 可滑动的顶部分类导航 -->
		<scroll-view class="category-nav" scroll-x="true">
			<view class="nav-item" v-for="(item, index) in categories" :key="index"
				:class="{'active': currentType === item.type}" @click="switchType(item.type)">
				{{ item.name }}
			</view>
		</scroll-view>

		<!-- 订单列表 -->
		<view class="order-list">
			<view v-for="(item, index) in orderList" :key="index" class="order-item" @click="toDetail(item)">
				<view class="order-info">
					<text class="order-number">订单号: {{ item.orderId }}</text>
					<text class="order-date">时间: {{ formatIsoTimeToLocal(item.createdAt) }}</text>
					<text class="order-total">原价: ¥{{ item.total }}</text>
					<text class="order-status">状态: {{ st(item.state) }}</text>
					<view class="order-status">
						<text class="order-state" v-if="item.paystate !== 0">付款状态: {{ pt(item.paystate) }}</text>
						<button v-if="item.state === '2'" class="logistics-button"
							@click.stop="viewLogistics(item)">查看物流</button>
					</view>

				</view>
			</view>
			<view style="text-align: center;" v-if="orderList.length === 0">
				暂无订单
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				currentType: 'all', // 当前选中的类型
				orderList: [

				], // 订单列表
				result: [],
				categories: [{
						name: '全部',
						type: 'all'
					},
					{
						name: '待付款',
						type: 'pendingPayment'
					},
					{
						name: '待发货',
						type: 'pendingDelivery'
					},
					{
						name: '待收货',
						type: 'pendingReceipt'
					},
					{
						name: '售后',
						type: 'afterSale'
					},
					// 更多分类...
				]
			};
		},
		methods: {
			switchType(type) {
				this.currentType = type;
				this.fetchOrders(type);
			},
			viewLogistics(item) {
				uni.setStorageSync("Logistics", item);
				// console.log("Logistics", item.data[0].trackingNumber)

				// 直接跳转到物流详情页面
				uni.navigateTo({
					url: '/pages/Logistics/Logistics'
				});
			},
			fetchOrders(type) {
				let url;
				switch (type) {
					case 'all':
						url = 'https://shop.flowergk.com/shop/wxapplet/searchallorderlist';
						break;
					case 'pendingPayment':
						url = 'https://shop.flowergk.com/shop/wxapplet/searchwaitorderlist';
						break;
					case 'pendingDelivery':
						url = 'https://shop.flowergk.com/shop/wxapplet/searchsendorderlist';
						break;
					case 'pendingReceipt':
						url = 'https://shop.flowergk.com/shop/wxapplet/searchgetorderlist';
						break;
					case 'afterSale':
						url = 'https://shop.flowergk.com/shop/wxapplet/searchrefundorderlist';
						break;
					default:
						return;
				}
				this.request(url);
			},
			request(url) {
				let userInfoFromStorage = uni.getStorageSync('userInfo');
				if (!userInfoFromStorage) {
					uni.showModal({
						title: '登录/注册',
						content: '登录使用完整功能',
						showCancel: true,
						cancelText: '取消',
						confirmText: '去登录',
						success: (res) => {
							if (res.confirm) {
								// console.log("确认");
								let pages = getCurrentPages();
								let currentRoute = pages[pages.length - 1].route;
								uni.setStorageSync("currentRoute", currentRoute);
								uni.redirectTo({
									url: '/pages/login/login'
								})
							} else if (res.cancel) {
								return
							}
						},

					})
					return;
				}
				uni.request({
					url: url,
					method: 'POST',
					data: {
						openId: uni.getStorageSync('openid')
					},
					success: (res) => {
						// console.log("res", res.data.data)
						this.result = res.data.data,
							this.orderList = this.process(this.result)
					},
					fail: (err) => {
						console.error('请求失败:', err);
						uni.showToast({
							title: '网络请求失败，请检查网络或链接的合法性',
							icon: 'none'
						});
					}
				});
			},
			toDetail(item) {
				uni.setStorageSync("orderDetail", item);
				// console.log("orderDetail", item)
				uni.navigateTo({
					url: '/pages/orderDetail/orderDetail'
				});
			},
			pt(pt) {
				switch (pt) {
					case 0:
						return "未付款";
					case 1:
						return "已付款";
					case 2:
						return "待退款";
					case 3:
						return "已退款";
					default:
						break;
				}
			},
			st(st) {
				switch (st) {
					case "0":
						return "待付款";
					case "1":
						return "待发货";
					case "2":
						return "待收货";
					case "3":
						return "已完成";
					default:
						break;
				}
			},
			formatIsoTimeToLocal(isoString) {
				const date = new Date(isoString);
				const year = date.getFullYear();
				const month = (date.getMonth() + 1).toString().padStart(2, '0');
				const day = date.getDate().toString().padStart(2, '0');
				const hour = date.getHours().toString().padStart(2, '0');
				const minute = date.getMinutes().toString().padStart(2, '0');
				const second = date.getSeconds().toString().padStart(2, '0');
				const localTime = `${year}/${month}/${day} ${hour}:${minute}:${second}`;
				return localTime;
			},
			process(arrayA) {
				// 创建一个空对象用于按orderId分类
				const classified = {};

				// 遍历数组A中的每个项
				arrayA.forEach(item => {
					// 检查orderId是否存在
					if (item.orderId) {
						// 如果classified对象中不存在这个orderId，则创建一个新的分类
						if (!classified[item.orderId]) {
							classified[item.orderId] = {
								orderId: item.orderId,
								total: 0,
								createdAt: item.createdAt,
								state: item.state,
								userAddress: item.userAddress,
								paystate: item.paystate,
								payMoney: 0,
								data: []
							};
						}
						// 将当前项添加到对应orderId的数据数组中，并累加totalMoney
						classified[item.orderId].data.push(item);
						classified[item.orderId].total += item.totalMoney;
						classified[item.orderId].payMoney += parseInt(item.payMoney);
					}
				});

				// 将分类后的对象转换成数组B的结构
				const arrayB = Object.values(classified);
				//  console.log("分类后:", arrayB);
				return arrayB;
			}
		},
		onShow() {
			const type = uni.getStorageSync('orderType') || 'all';
			this.currentType = type;
			this.orderList = [];
			this.fetchOrders(type);
		}
	};
</script>

<style>
	/* 订单列表样式 */
	.order-list {
		padding: 15px;
	}

	.order-item {
		display: flex;
		flex-direction: row;
		background-color: #fff;
		border-radius: 10px;
		box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
		margin-bottom: 15px;
		padding: 15px;
	}

	.order-image {
		width: 100px;
		height: 100px;
		border-radius: 10px;
		margin-right: 15px;
	}

	.order-info {
		flex: 1;
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.order-number,
	.order-date,
	.order-total,
	.order-status {
		color: #333;
		margin-bottom: 5px;
	}

	.order-total {
		color: #04BE02;
	}

	/* 顶部分类导航样式 */
	.category-nav {
		display: flex;
		overflow-x: auto;
		white-space: nowrap;
		padding: 10px 0;
		background-color: #fff;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
	}

	.nav-item {
		display: inline-block;
		font-size: 16px;
		color: #333;
		padding: 10px;
		margin-right: 20px;
	}

	.nav-item.active {
		color: #04BE02;
	}

	/* 物流信息样式 */
	.order-status {
		display: flex;
		/* 使用弹性布局 */
		align-items: center;
		/* 垂直居中 */
		justify-content: space-between;
		/* 元素之间的空间平均分布 */
	}

	.logistics-button {
		font-size: 14px;
		color: #04BE02;
		/* 蓝色通常用于链接 */

		cursor: pointer;
		/* 变成手指指针，表示这是可点击的 */
		margin-left: auto;
		/* 将按钮推向右侧 */
		margin-right: 0;
		/* 确保按钮右侧没有额外的间隙 */
	}

	/* 确保按钮不会与文本重叠 */
	.order-status-text {
		flex: 1;
		/* 允许文本占据剩余空间 */
	}
</style>